package top.healthylife.gateway.platform.baohu.api.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.gateway.core.util.SystemConfigUtils;
import top.healthylife.gateway.dto.request.req.ApiReqDto;
import top.healthylife.gateway.platform.baohu.api.config.SystemConfig;
import top.healthylife.gateway.platform.baohu.api.dto.BaofuReqDto;
import top.healthylife.gateway.platform.baohu.api.util.baofoo.FormatUtil;
import top.healthylife.gateway.platform.baohu.api.util.baofoo.HttpClient;
import top.healthylife.gateway.platform.baohu.api.util.baofoo.rsa.RsaCodingUtil;
import top.healthylife.gateway.platform.baohu.api.util.baofoo.rsa.SecurityUtil;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author cl
 * @version 1.0
 * @date 2020/4/10 15:58
 */
@Slf4j
public class BaofuUtil {
    final static String SUCCESS = "success";

    public static <T> T selectBaofoo(BaofuReqDto baofuReqDto, SystemConfig baofuSystemConfig, Class<T> cls) {
        TreeMap<String, String> tm = new TreeMap<>();
        tm.put("member_id", baofuSystemConfig.getMemberId());
        tm.put("terminal_id", baofuSystemConfig.getTerminalId());
        tm.put("data_type", "json");
        Map<String, Object> map = new HashMap<>(16);
        map.put("member_id", baofuSystemConfig.getMemberId());
        map.put("terminal_id", baofuSystemConfig.getTerminalId());
        map.put("trans_id", "Trans_ID" + IdUtil.simpleUUID());
        map.put("trade_date", new SimpleDateFormat(DatePattern.PURE_DATETIME_PATTERN).format(new Date()));
        map.put("acc_no", baofuReqDto.getBankNo());
        map.put("id_card", baofuReqDto.getIdNo());
        map.put("id_type", baofuReqDto.getIdType().toString());
        map.put("id_holder", baofuReqDto.getName());
        map.put("mobile", baofuReqDto.getPhone());
        // 101:借记卡 102:信用卡 本系统只支持 101:借记卡
        map.put("card_type", "101");
        map.put("valid_date", "");
        map.put("valid_no", "");
        map.put("verify_element", "1234");
        map.put("industry_type", "A1");
        JSONObject js = new JSONObject(map);
        String datacontent = null;
        try {
            //将字符串转换为byte数组
            byte[] bytes = Base64.getDecoder().decode(baofuSystemConfig.getPrivateKey().trim());
            //转化为输入流
            InputStream inputStream = new ByteArrayInputStream(bytes);
            datacontent = RsaCodingUtil.encryptByPriPfxFile(SecurityUtil.base64Encode(js.toString()), inputStream, baofuSystemConfig.getPripwd());
        } catch (Exception e) {
            throw new BusinessException("宝付加密异常");
        }
        log.debug("正在查询宝付 接口 进行四要素校验 请求参数: {}", tm);
        tm.put("data_content", datacontent);
        String post = HttpClient.sendRequest("POST", baofuSystemConfig.getUrl(), FormatUtil.coverMap2String(tm));
        JSONObject jsonObject = JSONObject.parseObject(post);
        if (jsonObject.getBoolean(SUCCESS)) {
            JSONObject data = jsonObject.getJSONObject("data");
            return data.toJavaObject(cls);
        }
        throw new BusinessException(jsonObject.getString("errorMsg"));
    }


    /**
     * 访问日志输出和配置获取
     *
     * @param baofuReqDeo 入参
     * @return
     */
    public static SystemConfig systemConfigInfo(ApiReqDto baofuReqDeo) {
        //可直接通过工具类获取这个对象
        SystemConfig o = (SystemConfig) SystemConfigUtils.get();
        log.info("收到请求参数为:{}", JSONObject.toJSONString(baofuReqDeo));
        log.info("收到请求参数为:{}", JSONObject.toJSONString(o));
        return o;
    }
}
